from rest_framework import serializers
from .models import Comment
from user_auth.serializers import UserProfileSerializer

class CommentSerializer(serializers.ModelSerializer):
    """评论序列化器"""
    user = UserProfileSerializer(read_only=True)
    replies = serializers.SerializerMethodField()
    
    class Meta:
        model = Comment
        fields = ['id', 'note', 'user', 'content', 'parent_comment', 'replies', 'created_at']
        read_only_fields = ['user', 'created_at', 'replies']
    
    def get_replies(self, obj):
        """获取评论的回复列表"""
        if obj.replies.exists():
            return CommentSerializer(obj.replies.all(), many=True, context=self.context).data
        return []
    
    def create(self, validated_data):
        """创建评论"""
        validated_data['user'] = self.context['request'].user
        
        # 检查父评论是否存在且属于同一笔记
        parent_comment = validated_data.get('parent_comment')
        note = validated_data.get('note')
        
        if parent_comment and parent_comment.note != note:
            raise serializers.ValidationError('父评论不属于该笔记')
        
        return super().create(validated_data)

class CommentCreateSerializer(serializers.ModelSerializer):
    """创建评论的序列化器"""
    parent_comment = serializers.PrimaryKeyRelatedField(
        queryset=Comment.objects.all(),
        required=False,
        allow_null=True
    )
    
    class Meta:
        model = Comment
        fields = ['note', 'content', 'parent_comment']
    
    def create(self, validated_data):
        """创建评论"""
        validated_data['user'] = self.context['request'].user
        return Comment.objects.create(**validated_data)